from flask import Blueprint, request, render_template,jsonify,redirect,url_for
from flask_login import login_user, LoginManager
from sqlalchemy.exc import SQLAlchemyError

from .forms import UserRegForm, UserLoginForm
from exts import db
from . import users_bp
from apps.users.models import User
from exts import mail
from flask_mail import Message
from blinker import Namespace
from apps import login_manager
# 用户认证的回调函数
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
#自定义信息

ns =Namespace()
s = ns.signal('reg')

@users_bp.route('/reg',methods=['GET','POST'])
def reg():
    if request.method == 'GET':
        form_obj = UserRegForm()
        return render_template('shop/reg.html',form_obj=form_obj)
    if request.method == 'POST':
        f = UserRegForm(request.form)
        if f.validate_on_submit():
            uname = f.username.data
            users = User.query.filter(User.username == uname).count()
            if users:
                info = '用户已存在'
            else:
                try:
                    user = User()
                    user.username = f.username.data
                    user.password = f.password.data
                    user.mobile = f.mobile.data
                    user.sex = 1
                    user.email = f.email.data
                    user.birthday = "2023-01-01"
                    user.level = 1
                    user.status = 1
                    db.session.add(user)
                    db.session.commit()
                    info = '注册成功,请登陆'
                    s.send("714716839@qq.com")
                    return redirect(url_for('users.login'))
                except SQLAlchemyError as e:
                    print(e)
                    return render_template("shop/reg.html", form_obj=f, info=e)
            return render_template("shop/reg.html", form_obj=f, info=info)
        else:
            errors = f.errors
            return render_template("shop/reg.html", form_obj=f, info=errors)

@users_bp.route("/login",methods=["GET","POST"])
def login():
    if request.method == "GET":
        f = UserRegForm()
        return render_template('shop/login.html', form_obj=f)
    if request.method == "POST":
        f = UserLoginForm(request.form)
        if f.validate_on_submit():
            username = f.username.data
            pwd=f.password.data
            user = User.query.filter(User.username==username,User.password==pwd).first()
            if user:
                print(user)
                login_user(user)
                return '登录成功，重定向到首页'
            return render_template('shop/login.html', form_obj=f,info="用户登录失败")
        else:
            errors = f.errors
            print(errors)
            return render_template("shop/login.html", form_obj=f, info=errors)

#注册回调函数
@s.connect
def send_email(recipient):
    print("来信号了")
    msg = Message("你好，感谢你的注册，我们将会为你提供更好的服务", recipients=[recipient])
    msg.body = "这是一封注册成功后欢迎的邮件"
    mail.send(msg)